<?php
namespace app\manage\controller;
use think\Log;
use think\Db;
use think\Queue;

class Admin extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        // 查询条件start
        $phone = input('phone');
        $map = [];
        if($phone != null){
            $map['phone'] = $phone;
        }
        // 查询条件end



        $count = model('Admin')->countNum($map,false);

        if(!in_array($this->uid,[1,2,3])){
            $map['a.id'] = ['gt',3];
        }

        $admins = model('Admin')->getAdminsByMap($map);

        $groups = model('AuthGroup')->getListByMap('','','',true);

//        if(!in_array($this->uid,[1,2,3])){
//            array_shift($groups);
//        }

        return $this->fetch('',[
            'admins' => $admins,
            'count' => $count,
            'groups' => $groups,
            'phone' => $phone
        ]);
    }




    public function edit()
    {
        $admin = model('Admin')->getAdminByID(input('id'));
        return self::showJsonReturnCodeData('1001',$admin,'');
    }



    public function save()
    {
        if(request()->isAjax()){
            Db::startTrans();
            try{
                $password = input('post.password');
                $id = input('post.id');
                $save_data['realname'] = input('post.realname');
                $save_data['phone'] = input('post.phone');
                $save_data['user_id'] = input('post.user_id');
                $save_data['db_type'] = input('post.db_type');
                $save_data['group_id'] = input('post.group_id');
                $save_data['tel'] = input('post.tel');

                if(isset($id) && $id){
                    $save_data['id'] = $id;
                    if(!empty($password)){
                        $save_data['salt'] = $this->builderRand(4);
                        $save_data['password'] = md5(input('post.password') . $save_data['salt']);
                    }
                }else{
                    $save_data['salt'] = $this->builderRand(4);
                    $save_data['password'] = md5(input('post.password') . $save_data['salt']);
                }
                $result = $this->editData(false,'Admin','Admin',$save_data);
                if($result['code'] == 1001){
                    if(isset($id) && $id){
                        $result['msg'] = '修改管理员成功';
                        $accessRes = Db::name('auth_group_access')->where('uid','=',$id)->update(['group_id'=>$save_data['group_id']]);
                        if($accessRes !== false){
                            Db::commit(); // 提交事务
                            $this->RecordSystemLog($this->uid,$this->behavior,'修改管理员【'.$save_data['realname'].'】成功');
                        }else{
                            Db::rollback(); // 回滚事务
                        }
                    }else{
                        $result['msg'] = '添加管理员成功';
                        $admin = model('Admin')->getInfoByMap(['phone'=>$save_data['phone']],'','',false);
                        $accessRes = Db::name('auth_group_access')->insert(['uid'=>$admin['id'],'group_id'=>$save_data['group_id']]);
                        if($accessRes !== false){
                            Db::commit(); // 提交事务
                            $this->RecordSystemLog($this->uid,$this->behavior,'添加管理员【'.$save_data['realname'].'】成功');
                        }else{
                            Db::rollback(); // 回滚事务
                        }
                    }
                }

                return $result;
            }catch (\Exception $e){
                Db::rollback(); // 回滚事务
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    //商务管理员消耗统计
    public function merchantMoney(){
        $name = input('name','');
        $times = input('times','');
        $pro_id = input('pro_id','');

        $map = [];
        $map1 = [];
        $map2 = [];

        if($name != ''){
            $map['realname'] = ['like','%'.$name.'%'];
        }

        if($pro_id != ''){
            $map2['a.pro_id'] =$pro_id;
        }

        if($times != ''){
            $time_arr = explode(' - ',$times);
            $map1['b.create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1].' 23:59:59')]];
        }


        $infos=Db::name('auth_group_access')->alias('a')->field('a.uid,b.realname,b.phone')
            ->join('admin b','a.uid=b.id')
            ->where($map)
            ->where('delete_time',null)
            ->where(function ($q){
                $q->where('group_id',1)->whereOr('group_id',4)->whereOr('group_id',5);
            })
            ->select();

        $all_mnum=0;
        $all_cnum=0;
        $all_money=0;
        $all_cmoney=0;
        $all_cfmoney=0;
        $all_balance=0;
        $all_song=0;
        $all_addbalance=0;
        $all_subbalance=0;
        $products = model('Product')->where('status',1)->column('name','id');

        foreach ($infos as &$v){
            $merchantArr=model('Merchant')->field('id,balance')->where('bind_aid|weihu_aid',$v['uid'])->select();
            $v['mnum']=0; // 商户数量
            $v['cnum']=0; // 分发数量
            $v['all_money']=0; // 分发消耗
            $v['chong_money']=0; // 充值账户币
            $v['chong_fmoney']=0; // 充值真实币
            $v['balance']=0; // 总余额（计算欠费）
            $v['song']=0; // 赠送账户币
            $v['song_rate']=0; // 赠送账户币比例 赠送比例
            $v['add_money']=0; // 总余额（不算欠费）
            $v['sub_money']=0; // 欠费金额
            $v['sub_money_rate']=0; // 欠费比例
            if($merchantArr){
                $arrId=array_column($merchantArr,'id');
                $v['mnum']=count($arrId);
                $money=model('ClueLog')->alias('a')
                    ->join('clue b','a.clue_id=b.id')
                    ->field('count(a.id) num,sum(a.price) price')
                    ->where('a.mer_id','in',$arrId)
                    ->where($map1)
                    ->where($map2)
                    ->find();
                $v['cnum']=isset($money['num'])?$money['num']:0;
                $v['all_money']=isset($money['price'])?$money['price']:0;
                $mChongzhi=model('charge')->alias('b')->field('sum(money) money,sum(fz_money) fz_money')->whereIn('mer_id',$arrId)->where($map1)->find();
                $v['chong_money']=!empty($mChongzhi['money'])?$mChongzhi['money']:0;
                $v['chong_fmoney']=!empty($mChongzhi['fz_money'])?$mChongzhi['fz_money']:0;
                $v['balance']=array_sum(array_column($merchantArr,'balance'));
                $v['song']=bcsub($v['chong_money'],$v['chong_fmoney'],2);
                if($v['chong_fmoney']>0){
                    $v['song_rate']=bcdiv( $v['song'],$v['chong_fmoney'],4)*100;
                }
                foreach ($merchantArr as $vv){
                    if($vv['balance']>0){
                        $v['add_money']=bcadd($v['add_money'],$vv['balance'],2);
                    }
                    if($vv['balance']<0){
                        $v['sub_money']=bcadd($v['sub_money'],$vv['balance'],2);
                    }
                }
                if($v['chong_money']>0){
                    $v['sub_money_rate']=bcdiv($v['sub_money'],$v['chong_money'],4)*100;
                }
            }
            $all_mnum+=$v['mnum'];
            $all_cnum+=$v['cnum'];
            $all_money=bcadd($all_money,$v['all_money'],2);
            $all_cmoney=bcadd($all_cmoney,$v['chong_money'],2);
            $all_cfmoney=bcadd($all_cfmoney,$v['chong_fmoney'],2);
            $all_balance=bcadd($all_balance,$v['balance'],2);
            $all_song=bcadd($all_song,$v['song'],2);
            $all_addbalance=bcadd($all_addbalance,$v['add_money'],2);
            $all_subbalance=bcadd($all_subbalance,$v['sub_money'],2);
        }

        if($all_cfmoney>0){
            $all_song_rate=bcdiv($all_song,$all_cfmoney,4)*100;
        }else{
            $all_song_rate=0;
        }

        return $this->fetch('',[
            'infos' => $infos,
            'name' => $name,
            'times' => $times,
            'all_mnum' => $all_mnum,
            'all_cnum' => $all_cnum,
            'all_money' => $all_money,
            'all_cmoney' => $all_cmoney,
            'all_cfmoney' => $all_cfmoney,
            'all_balance' => $all_balance,
            'all_addbalance' => $all_addbalance,
            'all_subbalance' => $all_subbalance,
            'all_song' => $all_song,
            'all_song_rate' => $all_song_rate,
            'products' => $products,
            'pro_id' => $pro_id,

        ]);
    }

    //币和损耗明细
    public function  priceDetails(){
        $aid = input('aid','');
        $times = input('times','');
        $type = input('type','');

        $map=[];
        if(!empty($aid)){
            $map['a.admin_id']=$aid;
        }
        if(!empty($times)){
            $time_arr = explode('+-+',$times);
            $map['a.clue_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1].' 23:59:59')]];
        }
        if(!empty($type)){
            $map['type']=$type;
        }

        $moneyCost=model('admin_clue_price')->alias('a')->field('sum(price) price,sum(true_price) true_price')->where($map)->find();
        $allprice=isset($moneyCost['price'])?$moneyCost['price']:0;//账户成本
        $alltprice=isset($moneyCost['true_price'])?$moneyCost['true_price']:0;//真实成本


        if($type==1){
            $infos=model('admin_clue_price')->alias('a')->field('a.*,b.mer_name')
                ->join('merchant b','b.id=a.mer_id','LEFT')
                ->where($map)
                ->paginate();
            foreach ($infos as &$v){
//                $v['create_time']=date('Y-m-d H:i:s',$v['create_time']);
                $v['clue_time']=date('Y-m-d H:i:s',$v['clue_time']);
            }
            $fname='admin/price_details';
        }else{
            $infos=model('admin_clue_price')->alias('a')->field('a.*')
//                ->join('merchant b','b.id=a.mer_id','LEFT')
                ->where($map)
                ->paginate();
            foreach ($infos as &$v){
//                $v['create_time']=date('Y-m-d H:i:s',$v['create_time']);
                $v['clue_time']=date('Y-m-d H:i:s',$v['clue_time']);
                if($v['loss_type']==1){
                    $v['loss_desc']='ROI空耗';
                }elseif ($v['loss_type']==2){
                    $v['loss_desc']='有规则空耗';
                }elseif ($v['loss_type']==3){
                    $v['loss_desc']='无规则空耗';
                }else{
                    $v['loss_desc']='';
                }
            }
            $fname='admin/price_details2';
        }
        return $this->fetch($fname,[
            'infos' => $infos,
            'times' => $times,
            'type' => $type,
            'allprice' => $allprice,
            'alltprice' => $alltprice,

        ]);
    }

    //欠费明细
    public function  oweDetails(){
        $aid = input('aid','');
        $times = input('times','');
        $type = input('type','');

        $map=[];
        $map6='';
//        if(!empty($aid)){
//            $map['a.admin_id']=$aid;
//        }
        if(!empty($times)){
            $time_arr = explode('+-+',$times);
//            $map['a.clue_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1].' 23:59:59')]];
            $map6 =' AND c.create_time between '.strtotime($time_arr[0]).' AND '.strtotime($time_arr[1].' 23:59:59');
        }
        if(!empty($type)){
            $map['type']=$type;
            $logType=$type;
        }else{
            $logType=0;
        }


        $merchantArr=model('Merchant')->field('id,balance')->where('bind_aid|weihu_aid',$aid)->select();


        if($merchantArr) {
            $arrId = array_column($merchantArr, 'id');
            $infos=model('merchant_balance_log')->alias('a')->field('a.type,a.mer_id,money,a.balance,a.create_time,a.remark,d.mer_name')
                ->join('(SELECT MAX(c.id) max_id FROM wy_merchant_balance_log as c WHERE c.type='.$type.$map6.'   GROUP BY c.mer_id) as b','b.max_id=a.id')
                ->join('merchant d','d.id=a.mer_id')
                ->whereIn('a.mer_id',$arrId)->where($map)->where('a.balance','<',0)->paginate();
        }else{
            $infos=model('merchant_balance_log')->alias('a')->field('a.type,a.mer_id,money,a.balance,a.create_time,a.remark,d.mer_name')
                ->join('(SELECT MAX(c.id) max_id FROM wy_merchant_balance_log as c WHERE c.type='.$type.$map6.'   GROUP BY c.mer_id) as b','b.max_id=a.id')
                ->join('merchant d','d.id=a.mer_id')
                ->where('a.mer_id',0)->where($map)->where('a.balance','<',0)->paginate();
        }

        foreach ($infos as &$v){
//                $v['create_time']=date('Y-m-d H:i:s',$v['create_time']);
//            $v['clue_time']=date('Y-m-d H:i:s',$v['clue_time']);
            if($v['type']==1){//1账户币2真实币3服务币
                $v['type_desc']='账户币';
            }elseif ($v['type']==2){
                $v['type_desc']='真实币';
            }elseif ($v['type']==3){
                $v['type_desc']='服务币';
            }
        }

        return $this->fetch('',[
            'infos' => $infos,
            'times' => $times,
            'type' => $type,

        ]);
    }

    public function merchantMoneyCost(){
        $name = input('name','');
        $times = input('times','');
        $pro_id = input('pro_id','');

        $map = [];
        $map1 = [];
        $map2 = [];
        $map3 = [];
        $map4 = [];
        $map5 = [];
        $map6 = '';
        $map7 = [];

        if($name != ''){
            $map['realname'] = ['like','%'.$name.'%'];
        }

        if($pro_id != ''){
            $map2['a.pro_id'] =$pro_id;
        }

        if($times != ''){
            $time_arr = explode(' - ',$times);
            $map1['b.create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1].' 23:59:59')]];
            $map4['a.create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1].' 23:59:59')]];
            $map5['create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1].' 23:59:59')]];
            $map7['create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1].' 23:59:59')]];
            $map3['a.clue_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1].' 23:59:59')]];
            $map6 ='AND c.create_time between '.strtotime($time_arr[0]).' AND '.strtotime($time_arr[1].' 23:59:59');

        }


        $infos=Db::name('auth_group_access')->alias('a')->field('a.uid,b.realname,b.phone')
            ->join('admin b','a.uid=b.id')
            ->where($map)
            ->where('delete_time',null)
            ->where(function ($q){
                $q->where('group_id',1)->whereOr('group_id',4)->whereOr('group_id',5);
            })
            ->select();

        $shunhaoMoney=Db::name('admin_clue_price')->alias('a')->field('sum(a.price) price,sum(a.true_price) true_price')->where('admin_id',0)->where($map3)->where('type',1)->find();

        $shunhaoPrice=isset($shunhaoMoney['price'])?$shunhaoMoney['price']:0;
        $shunhaoTruePrice=isset($shunhaoMoney['true_price'])?$shunhaoMoney['true_price']:0;

        $all_mnum=0;//商户数量
        $all_cnum=0;//线索数量
        $all_money=0;//分发总金额
        $all_cmoney=0;//账户成本
        $all_cfmoney=0;//真实成本
        $all_balance=0;//收益
        $all_song=0;//赠送
        $owe_money=0;//欠费
        $owe_money2=0;//欠费

        $sunhao_money=0;//损耗
        $tsunhao_money=0;//真损耗
        $truePriceSunhao=0;
        $fw_money=0;//充值服务币
        $AallMoneyDiv=0;
        $allMoneyDiv=0;

        $products = model('Product')->where('status',1)->column('name','id');

        foreach ($infos as &$v){
            $merchantArr=model('Merchant')->field('id,balance')->where('bind_aid|weihu_aid',$v['uid'])->select();
            $v['mnum']=0;
            $v['cnum']=0;
            $v['all_money']=0;
            $v['price']=0;
            $v['true_price']=0;
            $v['shouyi_money']=0;
            $v['shouyi_rate']=0;
            $v['song_money']=0;
            $v['owe_money']=0;
            $v['roi_money']=0;
            $v['price_sunhao']=0;
            $v['tprice_sunhao']=0;
            $v['truePriceSunhao']=0;
            $v['fw_money']=0;
            $v['owe_money2']=0;

            if($merchantArr){
                $arrId=array_column($merchantArr,'id');

//                 $v['owe_money']=Db::name('merchant_balance_log')->alias('a')
//                    ->join('(SELECT MAX(c.id) id,c.balance as max_id FROM wy_merchant_balance_log as c '.$map6.'   GROUP BY c.mer_id HAVING c.balance<0) as b','b.max_id=a.id')
//                    ->whereIn('a.mer_id',$arrId)->select();
//                dump($v['owe_money']);


                $v['fw_money']=model('charge')->whereIn('mer_id',$arrId)->where($map7)->sum('fw_money');


                $v['mnum']=count($arrId);//商户数量

                $money=model('ClueLog')->alias('a')
                    ->join('clue b','a.clue_id=b.id')
                    ->field('count(a.id) num,sum(a.price) price')->where('a.mer_id','in',$arrId)->where($map1)->where($map2)->find();
                $v['all_money']=isset($money['price'])?$money['price']:0;

                $moneyCost=Db::name('admin_clue_price')->alias('a')->field('sum(a.price) price,sum(a.true_price) true_price')->where('a.admin_id',$v['uid'])->where($map3)->where('type',1)->find();
                $v['price']=isset($moneyCost['price'])?$moneyCost['price']:0;//账户成本
                $v['true_price']=isset($moneyCost['true_price'])?$moneyCost['true_price']:0;//真实成本

                $sunhaoCost=Db::name('admin_clue_price')->alias('a')->field('sum(a.price) price,sum(a.true_price) true_price')->where('a.admin_id',$v['uid'])->where($map3)->where('type',2)->find();
                $v['price_sunhao']=isset($sunhaoCost['price'])?$sunhaoCost['price']:0;//损耗账户成本
                $v['tprice_sunhao']=isset($sunhaoCost['true_price'])?$sunhaoCost['true_price']:0;//损耗真实成本



                //赠送
                $v['song_money']=model('charge')->whereIn('mer_id',$arrId)->where('type',2)->where($map5)->sum('money');
                //欠费
                $v['owe_money']=abs(Db::name('merchant_balance_log')->alias('a')
                    ->join('(SELECT MAX(c.id) max_id FROM wy_merchant_balance_log as c WHERE c.type=2 '.$map6.' GROUP BY c.mer_id) as b','b.max_id=a.id')
                    ->whereIn('a.mer_id',$arrId)->where('a.type',2)->where('a.balance','<',0)->sum('a.balance'));

                //欠费
                $v['owe_money2']=abs(Db::name('merchant_balance_log')->alias('a')
                    ->join('(SELECT MAX(c.id) max_id FROM wy_merchant_balance_log as c WHERE c.type=1 '.$map6.' GROUP BY c.mer_id) as b','b.max_id=a.id')
                    ->whereIn('a.mer_id',$arrId)->where('a.type',1)->where('a.balance','<',0)->sum('a.balance'));


                //(真实币成本+真实币空耗成本
                $v['truePriceSunhao']=bcadd($v['true_price'],$v['tprice_sunhao'],2);

                $allMoneyDiv=bcadd(bcsub(bcsub($v['all_money'],$v['song_money'],2),$v['owe_money2'],2),$v['fw_money'],2);




//                dump($v['realname']);
//                dump($v['all_money']);
//                dump($v['song_money']);
//                dump($v['owe_money']);
//                dump($v['fw_money']);
//
//                dump($allMoneyDiv);

//                dump($v['realname']);
//                dump($allMoneyDiv);
//                dump($v['truePriceSunhao']);

                $v['shouyi_money']=bcsub($allMoneyDiv,$v['truePriceSunhao'],2);
//                dump($v['shouyi_money']);
//                if($v['all_money']>0){
//                    $allMoneyDiv=bcsub(bcsub($v['all_money'],$v['song_money'],2),$v['owe_money'],2);
                if($allMoneyDiv!=0){
//                        dump($v['shouyi_money']);
//                        dump($allMoneyDiv);
                    $v['shouyi_rate']=bcdiv($v['shouyi_money'],$allMoneyDiv,4)*100;
                }
//                }
                //(分发总金额-赠送金额+充值服务币-欠费金额)/(真实币成本+真实币空耗成本)
                if($v['truePriceSunhao']>0){
//                    $v['roi_money']=round(bcdiv(bcadd($v['shouyi_money'],$v['truePriceSunhao'],2),$v['truePriceSunhao'],3),2);
                    $v['roi_money']=round(bcdiv($allMoneyDiv,$v['truePriceSunhao'],3),2);
                }
            }
            $AallMoneyDiv=bcadd($AallMoneyDiv,$allMoneyDiv,2);
            $all_mnum+=$v['mnum'];
            $all_cnum+=$v['cnum'];
            $all_money=bcadd($all_money,$v['all_money'],2);
            $all_cmoney=bcadd($all_cmoney,$v['price'],2);
            $all_cfmoney=bcadd($all_cfmoney,$v['true_price'],2);
            $all_balance=bcadd($all_balance,$v['shouyi_money'],2);
            $all_song=bcadd($all_song,$v['song_money'],2);
            $owe_money=bcadd($owe_money,$v['owe_money'],2);
            $owe_money2=bcadd($owe_money2,$v['owe_money2'],2);
            $sunhao_money=bcadd($sunhao_money,$v['price_sunhao'],2);
            $tsunhao_money=bcadd($tsunhao_money,$v['tprice_sunhao'],2);
            $truePriceSunhao=bcadd($truePriceSunhao,$v['truePriceSunhao'],2);
            $fw_money=bcadd($fw_money,$v['fw_money'],2);

        }
        if($AallMoneyDiv!=0){
            $all_song_rate=bcdiv($all_balance,$AallMoneyDiv,4)*100;
        }else{
            $all_song_rate=0;
        }


        if($truePriceSunhao!=0){
            $roi_money=round(bcdiv(bcadd($all_balance,$truePriceSunhao,2),$truePriceSunhao,3),2);
        }else{
            $roi_money=0;
        }


//        return json($infos);

        return $this->fetch('admin/merchant_money_cost2',[
            'infos' => $infos,
            'name' => $name,
            'times' => $times,
            'all_mnum' => $all_mnum,
            'all_cnum' => $all_cnum,
            'all_money' => $all_money,
            'all_cmoney' => $all_cmoney,
            'all_cfmoney' => $all_cfmoney,
            'all_balance' => $all_balance,

            'all_song_rate' => $all_song_rate,
            'products' => $products,
            'pro_id' => $pro_id,
            'shunhaoPrice' => $shunhaoPrice,
            'shunhaoTruePrice' => $shunhaoTruePrice,
            'all_song' => $all_song,
            'owe_money' => $owe_money,
            'owe_money2' => $owe_money2,
            'roi_money' => $roi_money,
            'sunhao_money' => $sunhao_money,
            'tsunhao_money' => $tsunhao_money,
            'fw_money' => $fw_money,

        ]);
    }

}